﻿#include "DlgMenu.h"
#include <wx/sizer.h>
#include <wx/statbox.h>
#include <wx/stattext.h>
#include <wx/msgdlg.h>
#include <wx/filedlg.h>
#include <wx/dcclient.h>
#include <wx/image.h>
#include <wx/bitmap.h>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
//(*InternalHeaders(DlgMenu)
#include <wx/intl.h>
#include <wx/string.h>
//*)

//(*IdInit(DlgMenu)
//*)
const wxString CDlgMenu::TABLENAME=_T("menu");
const wxString WINDOWS_TEXT = _T("菜谱管理模块");
//控件ID
const long CDlgMenu::IDC_BTN_ADD_MOD= wxNewId();
const long CDlgMenu::IDC_BTN_EXIT= wxNewId();
const long CDlgMenu::IDC_BTN_SEARCH= wxNewId();
const long CDlgMenu::IDC_BTN_DEL= wxNewId();
const long CDlgMenu::IDC_BTN_PIC= wxNewId();
const long CDlgMenu::IDC_COMBO_SEARCH= wxNewId();
const long CDlgMenu::IDC_COMBO_TYPE= wxNewId();
const long CDlgMenu::IDC_EDIT_SEARCH= wxNewId();
const long CDlgMenu::IDC_RICHEDIT_MATERIAL= wxNewId();
const long CDlgMenu::IDC_RICHEDIT_REMARK= wxNewId();
const long CDlgMenu::IDC_EDIT_NAME= wxNewId();
const long CDlgMenu::IDC_PIC= wxNewId();
const long CDlgMenu::IDC_LIST= wxNewId();

BEGIN_EVENT_TABLE(CDlgMenu,wxDialog)
    //(*EventTable(DlgMenu)
    //*)
END_EVENT_TABLE()

CDlgMenu::CDlgMenu(wxWindow* parent,wxWindowID id,const wxPoint& pos,const wxSize& size)
    :m_addormod_(-1)
{
    //(*Initialize(DlgMenu)
    Create(parent, id, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE|wxMAXIMIZE_BOX|wxMINIMIZE_BOX, _T("id"));
    SetClientSize(wxDefaultSize);
    Move(wxDefaultPosition);
    //*)
    SetTitle(WINDOWS_TEXT);
    SetWindowStyle(GetWindowStyle()|wxRESIZE_BORDER|wxCLOSE_BOX|wxMAXIMIZE_BOX|wxMINIMIZE_BOX);
    CreateCtrlAndEvent();
    EnableAllCtrl(false);
    InitComboBoxAndListCtrl();
}

CDlgMenu::~CDlgMenu()
{
    //(*Destroy(DlgMenu)
    //*)
}

void CDlgMenu::CreateCtrlAndEvent()
{
    /////////创建控件并布局
    topSizer_=new wxBoxSizer(wxVERTICAL);//顶层窗口布局,从上到下包含每个了窗口布局
    wxBoxSizer *firSize=new wxBoxSizer(wxHORIZONTAL);
    wxFlexGridSizer *secSize=new wxFlexGridSizer(1,2,0,0);
    secSize->AddGrowableCol(1);
    secSize->AddGrowableRow(0);
    wxFlexGridSizer *thiSize=new wxFlexGridSizer(1,2,0,0);
    thiSize->AddGrowableCol(1);
    thiSize->AddGrowableRow(0);
    wxBoxSizer *bottomSize=new wxBoxSizer(wxHORIZONTAL);
    topSizer_->Add(firSize,0,wxEXPAND|wxALL,0);
    topSizer_->Add(secSize,10,wxEXPAND|wxALL,0);
    topSizer_->Add(thiSize,10,wxEXPAND|wxALL,0);
    topSizer_->Add(bottomSize,0,wxEXPAND|wxALL,0);

    wxFlexGridSizer *secSize_1=new wxFlexGridSizer(3,2,0,0);
    secSize_1->AddGrowableRow(1);
    wxStaticBox *staticBox=new wxStaticBox(this,wxID_ANY,wxT("简介"));
    wxStaticBoxSizer *secSize_2=new wxStaticBoxSizer(staticBox,wxHORIZONTAL);

    staticBox=new wxStaticBox(this,wxID_ANY,wxT("注意：双击列表数据可进行修改"));
    wxStaticBoxSizer *thiSize_1=new wxStaticBoxSizer(staticBox,wxHORIZONTAL);
    wxBoxSizer *thiSize_2=new wxBoxSizer(wxHORIZONTAL);

    combo_search_=new wxChoice(this,IDC_COMBO_SEARCH);
    combo_type_=new wxChoice(this,IDC_COMBO_TYPE);
    btn_Add_Mod_=new wxButton(this,IDC_BTN_ADD_MOD,_T("添加"));
    btn_Del_=new wxButton(this,IDC_BTN_DEL,_T("删除"));
    btn_Exit_=new wxButton(this,IDC_BTN_EXIT,_T("退出"));
    btn_Search_=new wxButton(this,IDC_BTN_SEARCH,_T("查询"));
    btn_pic_=new wxButton(this,IDC_BTN_PIC,_T("导入图片"));
    text_search_=new wxTextCtrl(this,IDC_EDIT_SEARCH,wxEmptyString);
    text_material_=new wxTextCtrl(this,IDC_RICHEDIT_MATERIAL,wxEmptyString,
                                  wxDefaultPosition,wxDefaultSize,wxTE_PROCESS_ENTER|wxTE_MULTILINE|wxHSCROLL);
    text_remark_=new wxTextCtrl(this,IDC_RICHEDIT_REMARK,wxEmptyString,
                                wxDefaultPosition,wxDefaultSize,wxTE_PROCESS_ENTER|wxTE_MULTILINE|wxHSCROLL);
    text_name_=new wxTextCtrl(this,IDC_EDIT_NAME,wxEmptyString);
    text_pic_=new wxStaticBitmap(this,IDC_PIC,wxBitmap());
    list_=new wxListCtrl(this,IDC_LIST,wxDefaultPosition,wxDefaultSize,wxLC_REPORT|wxLC_SINGLE_SEL);

    firSize->Add(new wxStaticText(this,wxID_ANY,_T("查询类别")),1, wxTILE|wxALL|wxALIGN_RIGHT,5);
    firSize->Add(combo_search_,1, wxEXPAND|wxALL|wxALIGN_CENTER,5);
    firSize->Add(text_search_,1,wxEXPAND|wxALL|wxALIGN_CENTER,5);
    firSize->Add(btn_Search_,1,wxTILE|wxALL|wxALIGN_LEFT,5);
    secSize->Add(secSize_1,1,wxEXPAND|wxALL|wxALIGN_RIGHT,5);
    secSize->Add(secSize_2,1,wxEXPAND|wxALL|wxALIGN_CENTER,5);
    secSize_1->Add(new wxStaticText(this,wxID_ANY,_T("菜名")),1,wxTILE|wxALL|wxALIGN_RIGHT,5);
    secSize_1->Add(text_name_,1,wxEXPAND|wxALL|wxALIGN_CENTER,5);
    secSize_1->Add(new wxStaticText(this,wxID_ANY,_T("材料")),1,wxTILE|wxALL|wxALIGN_RIGHT,5);
    secSize_1->Add(text_material_,1,wxEXPAND|wxALL|wxALIGN_CENTER,5);
    secSize_1->Add(new wxStaticText(this,wxID_ANY,_T("类别名称")),1,wxTILE|wxALL|wxALIGN_RIGHT,5);
    secSize_1->Add(combo_type_,1,wxEXPAND|wxALL|wxALIGN_CENTER,5);
    secSize_2->Add(text_remark_,1,wxEXPAND|wxALL|wxALIGN_CENTER,5);
    thiSize->Add(thiSize_1,1,wxEXPAND|wxALL|wxALIGN_RIGHT,5);
    thiSize->Add(thiSize_2,1,wxEXPAND|wxALL|wxALIGN_CENTER,5);
    thiSize_1->Add(list_,1,wxEXPAND|wxALL|wxALIGN_RIGHT,5);
    thiSize_2->Add(text_pic_,1,wxEXPAND|wxALL|wxALIGN_CENTER,5);
    bottomSize->Add(btn_Add_Mod_,1,wxTILE|wxALL|wxALIGN_RIGHT,5);
    bottomSize->Add(btn_Del_,1,wxTILE|wxALL|wxALIGN_CENTER,5);
    bottomSize->Add(btn_Exit_,1,wxTILE|wxALL|wxALIGN_LEFT,5);
    bottomSize->Add(btn_pic_,1,wxTILE|wxALL|wxALIGN_LEFT,5);

    SetSizer(topSizer_);//绑定对话框和布局控件
    SetAutoLayout(true);
    topSizer_->Fit(this);//调用对话框大小
    topSizer_->SetSizeHints(this);//设置对话框最小大小

    ///////创建事件
    Connect(IDC_BTN_ADD_MOD,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&CDlgMenu::OnBnClickedBtnAddMod);
    Connect(IDC_BTN_EXIT,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&CDlgMenu::OnBnClickedBtnExit);
    Connect(IDC_BTN_SEARCH,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&CDlgMenu::OnBnClickedBtnSearch);
    Connect(IDC_BTN_DEL,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&CDlgMenu::OnBnClickedBtnDel);
    Connect(IDC_BTN_PIC,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&CDlgMenu::OnBnClickedBtnPic);
    Connect(IDC_LIST,wxEVT_COMMAND_LIST_ITEM_SELECTED,(wxObjectEventFunction)&CDlgMenu::OnNMClickList);
    Connect(IDC_LIST,wxEVT_COMMAND_LIST_ITEM_ACTIVATED,(wxObjectEventFunction)&CDlgMenu::OnNMDblclkList);
    Connect(wxEVT_PAINT,(wxObjectEventFunction)&CDlgMenu::OnPaint);
    wxLogDebug(_T("CreateCtrl"));
}

void CDlgMenu::EnableAllCtrl( bool isEnable )
{
    if (m_addormod_==ADDMODEL) {
        FindWindowById(IDC_EDIT_NAME)->Enable(isEnable);
        FindWindowById(IDC_RICHEDIT_MATERIAL)->Enable(true);
        FindWindowById(IDC_COMBO_TYPE)->Enable(isEnable);
        FindWindowById(IDC_RICHEDIT_REMARK)->Enable(true);
        FindWindowById(IDC_BTN_PIC)->Enable(isEnable);
        FindWindowById(IDC_COMBO_SEARCH)->Enable(isEnable);
        FindWindowById(IDC_LIST)->Enable(false);
        FindWindowById(IDC_BTN_SEARCH)->Enable(false);
        FindWindowById(IDC_EDIT_SEARCH)->Enable(false);
        FindWindowById(IDC_BTN_DEL)->Enable(false);
    } else if (m_addormod_==MODMODEL) {
        FindWindowById(IDC_EDIT_NAME)->Enable(isEnable);
        FindWindowById(IDC_RICHEDIT_MATERIAL)->Enable(true);
        FindWindowById(IDC_COMBO_TYPE)->Enable(isEnable);
        FindWindowById(IDC_RICHEDIT_REMARK)->Enable(true);
        FindWindowById(IDC_BTN_PIC)->Enable(isEnable);
        FindWindowById(IDC_COMBO_SEARCH)->Enable(isEnable);
        FindWindowById(IDC_LIST)->Enable(false);
        FindWindowById(IDC_BTN_SEARCH)->Enable(false);
        FindWindowById(IDC_EDIT_SEARCH)->Enable(false);
        FindWindowById(IDC_BTN_DEL)->Enable(false);
    } else {
        FindWindowById(IDC_EDIT_NAME)->Enable(isEnable);
        FindWindowById(IDC_RICHEDIT_MATERIAL)->Enable(true);
        FindWindowById(IDC_COMBO_TYPE)->Enable(isEnable);
        FindWindowById(IDC_RICHEDIT_REMARK)->Enable(true);
        FindWindowById(IDC_BTN_PIC)->Enable(false);
        FindWindowById(IDC_COMBO_SEARCH)->Enable(true);
        FindWindowById(IDC_LIST)->Enable(true);
        FindWindowById(IDC_BTN_SEARCH)->Enable(true);
        FindWindowById(IDC_EDIT_SEARCH)->Enable(true);
        FindWindowById(IDC_BTN_DEL)->Enable(true);
    }
    wxLogDebug(_T("EnableAllCtrl"));
}

void CDlgMenu::InitComboBoxAndListCtrl()
{
    wxChoice *pchoice=wxDynamicCast(FindWindowById(IDC_COMBO_SEARCH),wxChoice);
    wxListCtrl *pList=wxDynamicCast(FindWindowById(IDC_LIST),wxListCtrl);
    pList->SetSingleStyle(wxLC_REPORT);
    pList->SetSingleStyle(wxLC_SINGLE_SEL);
    const vector<pair<wxString,wxString> >&chs_fileds_name=GetFiled_CHS_Name(_T("name_VmenuFull"));
    auto it=chs_fileds_name.cbegin();
    for (; it!=chs_fileds_name.cend(); ++it) {
        wxLogDebug(_T("%s "),it->first.c_str());
        pchoice->Append(it->first);
        pList->InsertColumn(pList->GetColumnCount(),it->first,wxLIST_FORMAT_LEFT,wxLIST_AUTOSIZE);
    }
    pchoice->Refresh();
    pList->Refresh();
    pchoice=wxDynamicCast(FindWindowById(IDC_COMBO_TYPE),wxChoice);
    wxString sql=_T("where typeid like '2%'");
    m_typenameandid_=GetTypeName_ID(sql);
    for(auto nameidit=m_typenameandid_.begin(); nameidit!=m_typenameandid_.end(); ++nameidit) {
        pchoice->Append(nameidit->first);
    }
    pchoice->Refresh();
    wxLogDebug(_T("InitComboBoxAndListCtrl"));
}

void CDlgMenu::OnBnClickedBtnSearch(wxCommandEvent& event)
{
    wxBusyCursor waticursor;
    wxChoice *pBox=wxDynamicCast(FindWindowById(IDC_COMBO_SEARCH),wxChoice);
    int index=pBox->GetSelection();
    wxString strComboTextFirst,strComboTextSecond;
    if (index == wxNOT_FOUND) {
        wxLogDebug(_T("查询类别为空"));
        //return;
    } else {
        strComboTextFirst=pBox->GetString(index);
    }
    const vector<pair<wxString,wxString> >&chs_filed_name=GetFiled_CHS_Name(_T("name_VmenuFull"));
    if (chs_filed_name.empty()) {
        return;
    }
    wxString sql=_T("select ");
    auto it=chs_filed_name.cbegin();
    for (; it!=chs_filed_name.cend(); ++it) {
        if (strComboTextFirst==it->first) {
            strComboTextSecond=it->second;
        }
        sql+=it->second+_T(",");
    }
    sql+=_T(" pic from VmenuFull");
    wxTextCtrl *pText=wxDynamicCast(FindWindowById(IDC_EDIT_SEARCH),wxTextCtrl);
    wxString csEditText=pText->GetValue();
    csEditText.Trim(true);
    csEditText.Trim(false);
    if (!csEditText.IsEmpty() && !strComboTextFirst.IsEmpty()) {
        sql+=_T(" where ")+strComboTextSecond;
        sql+=_T(" like '%")+csEditText+_T("%'");
    }
    wxListCtrl *pList=wxDynamicCast(FindWindowById(IDC_LIST),wxListCtrl);
    pList->DeleteAllItems();
    m_picdata_map_.clear();
    sqlite3_stmt *stmt;
    wxString menuid,menuname,menutypename,material,remark;
    if(sqlite3_prepare_v2(g_db,ToDefaultConv(sql),LenDefaultConv(sql),&stmt,0)==SQLITE_OK) {
        size_t row_count=0;
        while(sqlite3_step(stmt)==SQLITE_ROW) { //找到记录
            pList->InsertItem(row_count,_T(""));
            menuid=wxString((const char*)sqlite3_column_text(stmt,0), DefaultConv);
            menuname=wxString((const char*)sqlite3_column_text(stmt,1), DefaultConv);
            material=wxString((const char*)sqlite3_column_text(stmt,2), DefaultConv);
            menutypename=wxString((const char*)sqlite3_column_text(stmt,3), DefaultConv);
            remark=wxString((const char*)sqlite3_column_text(stmt,4), DefaultConv);
            wxMemoryBuffer buf;
            buf.AppendData((const char*)sqlite3_column_blob(stmt,5), sqlite3_column_bytes(stmt,5));
            //picdata=wxString::From8BitData((const char*)sqlite3_column_blob(stmt,5), sqlite3_column_bytes(stmt,5));
            wxLogDebug(_T("id=%s, data=%s, size=%d, memdata=%s, memsize=%d"),menuid.c_str(),(const char*)sqlite3_column_blob(stmt,5),
                       sqlite3_column_bytes(stmt,5),(const char*)buf.GetData(),buf.GetDataLen());
            pList->SetItem(row_count,0, menuid);
            pList->SetItem(row_count,1, menuname);
            pList->SetItem(row_count,2, material);
            pList->SetItem(row_count,3, menutypename);
            pList->SetItem(row_count,4, remark);
            m_picdata_map_[menuid]=buf;
        }
        if (sqlite3_finalize(stmt) != SQLITE_OK) {
            wxLogDebug(_T("Error on sqlite3_finalize: %s"), sqlite3_errmsg(g_db));
        }
    } else {
        wxLogDebug(_T("%s 语法有误. 错误信息:%s"), sql.c_str(),sqlite3_errmsg(g_db));
        if (sqlite3_finalize(stmt) != SQLITE_OK) {
            wxLogDebug(_T("Error on sqlite3_finalize: %s"), sqlite3_errmsg(g_db));
        }
    }
    pList->SetColumnWidth(0,wxLIST_AUTOSIZE);
    wxLogDebug(_T("OnBnClickedBtnSearch"));
}
void CDlgMenu::OnBnClickedBtnDel(wxCommandEvent& event)
{
    wxListCtrl *pList=wxDynamicCast(FindWindowById(IDC_LIST),wxListCtrl);
    long selitemIndex=-1;
    selitemIndex=pList->GetNextItem(selitemIndex,wxLIST_NEXT_ALL,wxLIST_STATE_SELECTED);//得到选中的行数
    if (selitemIndex ==-1) {
        return;
    }
    wxString csid=pList->GetItemText(selitemIndex,0);
    wxString csname=pList->GetItemText(selitemIndex,1);
    wxString tip=_T("确实要删除编号为[")+csid+_T("],菜名为[")+csname+_T("]的菜谱吗？");
    if(wxNO==wxMessageBox(tip,_T("删除确认"),wxYES_NO)) {
        return;
    }
    map<wxString,wxString> condition;
    condition[_T("menuid")]=m_keyvalue_;
    if(DelFromDb(TABLENAME,&condition)) {
        wxMessageBox(_T("删除完成"),_T("删除完成"),wxOK);
        pList->DeleteItem(selitemIndex);
        m_picdata_map_.erase(csid);
    } else {
        wxMessageBox(sqlite3_errmsg(g_db),_T("删除出错"));
        return;
    }
    wxLogDebug(_T("OnBnClickedBtnDel"));
}
void CDlgMenu::OnBnClickedBtnExit(wxCommandEvent& event)
{
    if (ADDMODEL==m_addormod_ || MODMODEL==m_addormod_) {
        m_addormod_=-1;
        EnableAllCtrl(false);
        wxButton *pbtn=wxDynamicCast(FindWindowById(IDC_BTN_ADD_MOD),wxButton);
        pbtn->SetLabel(_T("添加"));
        pbtn=wxDynamicCast(FindWindowById(IDC_BTN_EXIT),wxButton);
        pbtn->SetLabel(_T("退出"));
        SetLabel(WINDOWS_TEXT);
    } else {
        Close();
    }
    wxLogDebug(_T("OnBnClickedBtnExit"));
}

void CDlgMenu::OnBnClickedBtnPic(wxCommandEvent& event)
{
    wxBusyCursor wait;
    wxString caption = wxT("选择照片");
    wxString wildcard = wxT("照片(*.jpg;*.png;*.bmp)|*.jpg;*.png;*.bmp|所有文件(*.*)|*.*");
    wxString defaultDir=wxT("");
    wxString defaultFileName = wxT("");
    wxFileDialog dialog(this,caption,defaultDir,defaultFileName,wildcard,wxFD_OPEN);
    if( dialog.ShowModal() == wxID_OK) {
        wxString FilePath_Name = dialog.GetPath();
        wxLogDebug(_T("start load img %s"),FilePath_Name.mb_str().data());
        m_img_=cv::imread(FilePath_Name.ToStdString());
        wxLogDebug(_T("end load img %s, w=%d,h=%d"),FilePath_Name.mb_str().data(),m_img_.cols,m_img_.rows);
        wxRect rc=FindWindowById(IDC_PIC)->GetRect();
        this->Refresh(true,&rc);
        this->Update();
    }
    wxLogDebug(_T("OnBnClickedBtnPic"));
}

void CDlgMenu::OnBnClickedBtnAddMod(wxCommandEvent& event)
{
    wxString sql;
    if(ADDMODEL ==m_addormod_ || MODMODEL ==m_addormod_) {
        sqlite3_stmt *stmt;
        wxTextCtrl *pText=wxDynamicCast(FindWindowById(IDC_EDIT_NAME),wxTextCtrl);
        wxString csTypeName=pText->GetValue();
        if(csTypeName.IsEmpty()) {
            wxMessageBox(_T("菜名不能为空"),_T("错误"),wxOK);
            return;
        }
        int nIdx=-1;//行索引
        wxString menuid,menutypename,material,remark;
        wxMemoryBuffer picdata;
        switch (m_addormod_) {
        case MODMODEL:
            menuid=m_keyvalue_;
            break;
        case ADDMODEL: {
            wxString sql=_T("select count(menuname) from ")+TABLENAME;
            sql+=_T(" where menuname = '")+csTypeName+_T("'");
            if(sqlite3_prepare_v2(g_db,ToDefaultConv(sql),LenDefaultConv(sql),&stmt,0)==SQLITE_OK) {
                if(sqlite3_step(stmt)==SQLITE_ROW) { //找到记录
                    if(sqlite3_column_int(stmt,0)>0) {
                        wxMessageBox(_T("该菜名已存在,不允许添加，请使用其他的菜名。"),_T("菜名重复"),wxOK);
                        if (sqlite3_finalize(stmt) != SQLITE_OK) {
                            wxLogDebug(_T("Error on sqlite3_finalize: %s"), sqlite3_errmsg(g_db));
                        }
                        return;
                    }
                }
                if (sqlite3_finalize(stmt) != SQLITE_OK) {
                    wxLogDebug(_T("Error on sqlite3_finalize: %s"), sqlite3_errmsg(g_db));
                }
            } else {
                wxLogDebug(_T("%s 语法有误. 错误信息:%s"), sql,sqlite3_errmsg(g_db));
                if (sqlite3_finalize(stmt) != SQLITE_OK) {
                    wxLogDebug(_T("Error on sqlite3_finalize: %s"), sqlite3_errmsg(g_db));
                }
            }
            wxDateTime theday=wxDateTime::Today();
            wxString csday=theday.Format(_T("%Y%m%d"));
            sql=_T("select max(menuid) from ")+TABLENAME;
            sql+=_T(" where menuid like '")+csday+_T("%'");
            if(sqlite3_prepare_v2(g_db,ToDefaultConv(sql),LenDefaultConv(sql),&stmt,0)==SQLITE_OK) {
                if(sqlite3_step(stmt)==SQLITE_ROW) { //找到记录
                    if(sqlite3_column_text(stmt,0)!=NULL) {
                        wxString maxid=wxString((const char*)sqlite3_column_text(stmt,0),DefaultConv);
                        menuid=maxid.substr(8,maxid.length());//得到最后四位序号
                        long nid;
                        menuid.ToLong(&nid);
                        ++nid;
                        menuid=wxString::Format(_T("%s%04d"),csday,nid);
                    } else { //当天第一条记录
                        menuid=csday+_T("0001");
                    }
                }
                if (sqlite3_finalize(stmt) != SQLITE_OK) {
                    wxLogDebug(_T("Error on sqlite3_finalize: %s"), sqlite3_errmsg(g_db));
                }
            } else {
                wxLogDebug(_T("%s 语法有误. 错误信息:%s"), sql,sqlite3_errmsg(g_db));
                if (sqlite3_finalize(stmt) != SQLITE_OK) {
                    wxLogDebug(_T("Error on sqlite3_finalize: %s"), sqlite3_errmsg(g_db));
                }
            }
        }
        break;
        default:
            break;
        }
        material=wxDynamicCast(FindWindowById(IDC_RICHEDIT_MATERIAL),wxTextCtrl)->GetValue();
        remark=wxDynamicCast(FindWindowById(IDC_RICHEDIT_REMARK),wxTextCtrl)->GetValue();
        wxChoice* pBox=wxDynamicCast(FindWindowById(IDC_COMBO_TYPE),wxChoice);
        menutypename=pBox->GetStringSelection();
        wxLogDebug(_T("material=%s,remark=%s"),material,remark);
        ////由类别名称查找类别ID
        bool isfindtypeID=false;
        int typeID;
        sql=_T(" where typename='")+menutypename+_T("'");
        auto typename_id=GetTypeName_ID(sql);
        for (auto it=typename_id.cbegin(); it!=typename_id.cend(); ++it) {
            if (it->first==menutypename) {
                typeID=it->second;
                isfindtypeID=true;
                break;
            }
        }
        if (isfindtypeID==false) {
            wxMessageBox(_T("类别名称有误，请重新选择"),_T("由类别名称查找类别ID出错"),wxOK);
            return;
        }
        vector<unsigned char>buf;
        if (!m_img_.empty()) {
            wxLogDebug(_T("start encode"));
            cv::imencode(".jpg", m_img_, buf);//将图像数据解码成jpg格式
            wxLogDebug(_T("end encode "));
            picdata.AppendData((const char*)&*buf.begin(),buf.size());
            wxLogDebug(_T("picdata=%s,datasize=%d,bufsize=%d"),(const char*)picdata.GetData(),picdata.GetDataLen(),buf.size());
        }
        wxListCtrl* pList=wxDynamicCast(FindWindowById(IDC_LIST),wxListCtrl);
        if (ADDMODEL==m_addormod_) { //由添加转为完成
            //添加新记录
            sql=_T("insert into ")+TABLENAME;
            sql+=_T(" (menuid,menuname,material,pic,typeid,remark) ");
            sql+=_T(" values(@pa1,@pa2,@pa3,@pa4,@pa5,@pa6)");
        } else if (MODMODEL==m_addormod_) { //由修改转为完成
            sql=_T("update ")+TABLENAME;
            sql+=_T(" set menuname=@pa2,material=@pa3,");
            sql+=_T("pic=@pa4,typeid=@pa5,remark=@pa6 where menuid=@pa1");
        }
        int index1=0;
        if(sqlite3_prepare_v2(g_db,ToDefaultConv(sql),LenDefaultConv(sql),&stmt,0)==SQLITE_OK) {
            index1 = sqlite3_bind_parameter_index(stmt, "@pa1");
            if(sqlite3_bind_text(stmt, index1, ToDefaultConv(menuid), LenDefaultConv(menuid), SQLITE_STATIC)!=SQLITE_OK) {
                wxLogDebug(_T("sqlite3_bind_text on menuid Error on. %s"), sqlite3_errmsg(g_db));
            }
            index1 = sqlite3_bind_parameter_index(stmt, "@pa2");
            if(sqlite3_bind_text(stmt, index1, ToDefaultConv(csTypeName), LenDefaultConv(csTypeName), SQLITE_STATIC)!=SQLITE_OK) {
                wxLogDebug(_T("sqlite3_bind_text on menuname Error on. %s"), sqlite3_errmsg(g_db));
            }
            index1 = sqlite3_bind_parameter_index(stmt, "@pa3");
            if(sqlite3_bind_text(stmt, index1, ToDefaultConv(material), LenDefaultConv(material), SQLITE_STATIC)!=SQLITE_OK) {
                wxLogDebug(_T("sqlite3_bind_text on material Error on. %s"), sqlite3_errmsg(g_db));
            }
            index1 = sqlite3_bind_parameter_index(stmt, "@pa4");
            if(sqlite3_bind_blob(stmt, index1,(const char*)picdata.GetData(),picdata.GetDataLen(), SQLITE_STATIC)!=SQLITE_OK) {
                wxLogDebug(_T("sqlite3_bind_parameter_blob on pic Error on. %s"), sqlite3_errmsg(g_db));
            }
            index1 = sqlite3_bind_parameter_index(stmt, "@pa5");
            if(sqlite3_bind_int(stmt, index1, typeID)!=SQLITE_OK) {
                wxLogDebug(_T("sqlite3_bind_parameter_int on typeid Error on. %s"), sqlite3_errmsg(g_db));
            }
            index1 = sqlite3_bind_parameter_index(stmt, "@pa6");
            if(sqlite3_bind_text(stmt, index1, ToDefaultConv(remark), LenDefaultConv(remark), SQLITE_STATIC)!=SQLITE_OK) {
                wxLogDebug(_T("sqlite3_bind_text on remark Error on. %s"), sqlite3_errmsg(g_db));
            }

            // commit
            sqlite3_step(stmt);
            if (sqlite3_finalize(stmt) != SQLITE_OK) {
                wxLogDebug(_T("Error on sqlite3_finalize: %s"), sqlite3_errmsg(g_db));
            }
        } else {
            wxLogDebug(_T("%s 语法有误. 错误信息:%s"), sql,sqlite3_errmsg(g_db));
            if (sqlite3_finalize(stmt) != SQLITE_OK) {
                wxLogDebug(_T("Error on sqlite3_finalize: %s"), sqlite3_errmsg(g_db));
            }
        }

        if (ADDMODEL==m_addormod_) {
            //成功把该行插入到list控件中
            pList->InsertItem(pList->GetItemCount(),_T(""));
            nIdx=pList->GetItemCount()-1;
        } else if (MODMODEL==m_addormod_) {
            //成功把修改结果反应到list控件中
            nIdx=-1;
            nIdx = pList->GetNextItem(nIdx,wxLIST_NEXT_ALL,wxLIST_STATE_SELECTED);
            if(nIdx == -1) {
                return;
            }
        }
        wxLogDebug(_T("select id=%d"),nIdx);
        pList->SetItem(nIdx,0,menuid);
        pList->SetItem(nIdx,1,csTypeName);
        pList->SetItem(nIdx,2,material);
        pList->SetItem(nIdx,3,menutypename);
        pList->SetItem(nIdx,4,remark);
        m_picdata_map_[menuid]=picdata;
        m_addormod_=-1;
        EnableAllCtrl(false);
        wxButton *pbtn=wxDynamicCast(FindWindowById(IDC_BTN_ADD_MOD),wxButton);
        pbtn->SetLabel(_T("添加"));
        pbtn=wxDynamicCast(FindWindowById(IDC_BTN_EXIT),wxButton);
        pbtn->SetLabel(_T("退出"));
        SetLabel(WINDOWS_TEXT);
    } else {
        m_addormod_=ADDMODEL;
        EnableAllCtrl(true);
        wxButton *pbtn=wxDynamicCast(FindWindowById(IDC_BTN_ADD_MOD),wxButton);
        pbtn->SetLabel(_T("完成"));
        pbtn=wxDynamicCast(FindWindowById(IDC_BTN_EXIT),wxButton);
        pbtn->SetLabel(_T("取消添加"));
        SetLabel(WINDOWS_TEXT+_T("_添加"));
        wxTextCtrl *pText=wxDynamicCast(FindWindowById(IDC_EDIT_NAME),wxTextCtrl);
        pText->SetLabel(_T(""));
    }
    wxLogDebug(_T("OnBnClickedBtnAddMod"));
}
void CDlgMenu::OnNMClickList(wxListEvent& event)
{
    if(event.GetIndex()==-1) {
        return;
    }
//    cv::Mat img=cv::imread("D:/1.jpg");
//    //cv::imshow("img",img);
//    vector<unsigned char>buff;
//    if (!img.empty()) {
//        cv::imencode(".jpg", img, buff);//将图像数据解码成jpg格式
//    }
////    img = cv::imdecode(cv::Mat(buff), 1);
//    cv::imshow("img2",img);
    wxListCtrl *pList=wxDynamicCast(FindWindowById(IDC_LIST),wxListCtrl);
    m_keyvalue_=pList->GetItemText(event.GetIndex(),0);//得到主键值
    wxTextCtrl *pText=wxDynamicCast(FindWindowById(IDC_EDIT_NAME),wxTextCtrl);
    pText->SetValue(pList->GetItemText(event.GetIndex(),1));
    pText=wxDynamicCast(FindWindowById(IDC_RICHEDIT_MATERIAL),wxTextCtrl);
    pText->SetValue(pList->GetItemText(event.GetIndex(),2));
    wxChoice *pBox=wxDynamicCast(FindWindowById(IDC_COMBO_TYPE),wxChoice);
    pBox->SetStringSelection(pList->GetItemText(event.GetIndex(),3));
    pText=wxDynamicCast(FindWindowById(IDC_RICHEDIT_REMARK),wxTextCtrl);
    pText->SetValue(pList->GetItemText(event.GetIndex(),4));
    wxMemoryBuffer strpicdata=m_picdata_map_[m_keyvalue_];
    if (!strpicdata.IsEmpty()) {
        char* pdata=(char*)strpicdata.GetData();
        size_t ldata=strpicdata.GetDataLen();
        vector<unsigned char> buf(pdata,pdata+ldata);
        wxLogDebug(_T("vecsize=%d,bufsize=%d"),buf.size(),ldata);
        m_img_ = cv::imdecode(cv::Mat(buf), 1);
        wxLogDebug(_T("picdatasize=%d,matW=%d,matH=%d,bufsize=%d"),strpicdata.GetDataLen(),
                   m_img_.cols,m_img_.rows,buf.size());
        wxRect rc=FindWindowById(IDC_PIC)->GetRect();
        this->Refresh(true,&rc);
        this->Update();
    }
    wxLogDebug(_T("OnNMClickList"));
}
void CDlgMenu::OnNMDblclkList(wxListEvent& event)
{
    if(event.GetIndex()==-1) {
        return;
    }
    wxListCtrl *pList=wxDynamicCast(FindWindowById(IDC_LIST),wxListCtrl);
    m_keyvalue_=pList->GetItemText(event.GetIndex(),0);//得到主键值
    m_addormod_=MODMODEL;
    EnableAllCtrl(true);
    wxButton *pbtn=wxDynamicCast(FindWindowById(IDC_BTN_ADD_MOD),wxButton);
    pbtn->SetLabel(_T("保存"));//修改完回到待增加状态
    pbtn=wxDynamicCast(FindWindowById(IDC_BTN_EXIT),wxButton);
    pbtn->SetLabel(_T("取消修改"));
    wxString text=WINDOWS_TEXT+_T("_修改");
    SetLabel(text);
    wxLogDebug(_T("OnNMDblclkList"));
}

void CDlgMenu::OnPaint(wxPaintEvent& event)
{
    if (!m_img_.empty()) {
        wxStaticBitmap *pbmp=wxDynamicCast(FindWindowById(IDC_PIC),wxStaticBitmap);
        wxSize pic_size=pbmp->GetSize();
        cv::Mat tmpMat(pic_size.GetHeight(),pic_size.GetWidth(),CV_8UC3);
        cv::resize(m_img_,tmpMat,tmpMat.size());
        cv::cvtColor(tmpMat,tmpMat,CV_BGR2RGB);
        wxImage wx_img(tmpMat.cols,tmpMat.rows,tmpMat.data,true);
        wxBitmap wx_bmp(wx_img,tmpMat.depth());
        pbmp->SetBitmap(wx_bmp);
    } else {
        wxStaticBitmap *pbmp=wxDynamicCast(FindWindowById(IDC_PIC),wxStaticBitmap);
        pbmp->SetBitmap(wxBitmap());
    }
    wxLogDebug(_T("OnPaint"));
}














